package workers;

import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import protocol.TransferenciaClienteServidor;
import application.MachineID;
import application.UniqueFileID;

@SuppressWarnings("unused")
public class ClientDownloadWorker extends TimedWorker implements Runnable {

	File destino;
	String filenameToDownload;
	MachineID machineID;
	UniqueFileID uniqueFileID;
	TransferenciaClienteServidor tcs;
	
	public ClientDownloadWorker( File fDestino, UniqueFileID fid, PropertyChangeListener changeListener ){
		super( "Descargar " + fid.getFileName() + " de " + fid.getMachineID().toString(), changeListener);
		filenameToDownload = fid.getFileName();
		destino = fDestino;
		this.machineID = fid.getMachineID();
		setCurrentAction("waiting for turn in poool");
		uniqueFileID = fid;
		tcs= null;
	}
	
	
	@Override
	public void run() {
		setCurrentAction("running");
		try {
			Socket s = machineID.createSocket();
			startWork();
			assert s.isConnected();
			tcs = new TransferenciaClienteServidor( s , destino  , filenameToDownload , this, uniqueFileID , 0 );
			tcs.run();
			s.shutdownInput();
			s.shutdownOutput();
			s.close();
			//setCurrentAction("socket shut down and closed");
			stopWork();
//		} catch (UnknownHostException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
		} catch ( Exception e ){
			e.printStackTrace();
			setCurrentAction("failed with " + e.getClass().getCanonicalName());
		}
	}


	@Override
	public void cancelTask() {
		setCanceled(true);
		if(tcs!= null){
			tcs.setCancelTransfer();
		}
	}
}
